import json

from django.contrib.auth import logout
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.generics import RetrieveAPIView, UpdateAPIView, ListAPIView
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from question.models import Question, Reply
from recruit.models import Recruit, Enterprise
from users.models import User
from users.serializers.user_admin import UserAdminSerializer, UserLabelSerializer, UserQuestionSerializer, \
    AnswerQuestionSerializer


# 用户中心
# class UserDetailView(APIView):
#     """用户中心"""
#
#     def get(self, request):
#         # 获取请求用户对象
#         user = request.user
#         # 获取用户关注的标签
#         user_labels = user.labels.all()
#         labels = []
#         for label in user_labels:
#             labels.append(label.label_name)
#         # 获取用户的问题
#         user_questions = Question.objects.filter(user_id=user.id)
#         questions = []
#         for question in user_questions:
#             questions.append(question.title)
#         # 获取用户的回答
#         user_reply = Reply.objects.filter(user_id=user.id)
#         answer_question = []
#         for reply in user_reply:
#             answer_question.append(reply.content)
#         # 获取用户收藏的文章
#         collected_articles = []
#         user_articles = user.collected_articles.all()
#         for article in user_articles:
#             collected_articles.append(article.title)
#         # 获取用户的企业
#         user_enterpises = user.enterpises.all()
#         enterpises = []
#         for enterpise in user_enterpises:
#             recruits = []
#             enterpise_recruits = Recruit.objects.filter(enterprise_id=enterpise.id)
#             for i in enterpise_recruits:
#                 recruits.append(i.id)
#             enterpises.append({'id': enterpise.id,
#                                'name': enterpise.name,
#                                'labels': enterpise.labels,
#                                'logo': enterpise.logo,
#                                'recruits': recruits,
#                                'summary': enterpise.summary})
#         # 构建响应数据
#         data = {'id': user.id,
#                 'username': user.username,
#                 'mobile': user.mobile,
#                 'realname': user.realname,
#                 'birthday': user.birthday,
#                 'sex': user.sex,
#                 'avatar': user.avatar,
#                 'website': user.website,
#                 'email': user.email,
#                 'city': user.city,
#                 'address': user.address,
#                 'labels': labels,
#                 'questions': questions,
#                 'answer_question': answer_question,
#                 'collected_articles': collected_articles,
#                 'enterpises': enterpises}
#         return Response(data)

class UserDetailView(ListAPIView, UpdateAPIView):
    serializer_class = UserAdminSerializer

    def get_queryset(self):

        queryset = User.objects.filter(id=self.request.user.id)
        return queryset

    # 详情
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)


        data_dict = serializer.data[0]

        user = request.user

        # 查询用户所有回答
        try:
            replys = Reply.objects.filter(user_id=user.id)
        except Exception as e:
            return JsonResponse({'message': '查询错误', 'success': False})

        data_list = []
        for reply in replys:

            # 回答的问题
            question = reply.problem
            question_serializer = UserQuestionSerializer(question)
            answer_question = question_serializer.data
            data_list.append(answer_question)

        data_dict['answer_question'] = data_list

        return Response(data_dict)

    # 更新
    def update(self, request, *args, **kwargs):
        # 获取用户
        user = request.user

        # 获取用户信息
        request.data['password'] = user.password
        request.data['username'] = user.username

        request.data['fans'] = [1]

        partial = kwargs.pop('partial', False)
        instance = request.user
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            print(e)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)


# # 详情
# class UserAdminView(ModelViewSet):
#     serializer_class = UserAdminSerializer
#     queryset = User.objects.all()
#
#     # 修改个人信息
#     def retrieve(self, request, *args, **kwargs):
#         instance = self.get_object()
#         serializer = self.get_serializer(instance)
#         return Response(serializer.data)
#
#     # 获取个人信息
#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         serializer = self.get_serializer(queryset, many=True)
#         data_dict = serializer.data[0]
#
#         user = request.user
#
#         # 查询用户所有回答
#         try:
#             replys = Reply.objects.filter(user_id=user.id)
#         except Exception as e:
#             return JsonResponse({'message': '查询错误', 'success': False})
#
#         data_list = []
#         for reply in replys:
#             # reply_serializer = AnswerQuestionSerializer(reply)
#             # answer_question = reply_serializer.data
#             # data_list.append(answer_question)
#
#             # 回答的问题
#             question = reply.problem
#             question_serializer = UserQuestionSerializer(question)
#             answer_question = question_serializer.data
#             data_list.append(answer_question)
#
#         data_dict['answer_question'] = data_list
#
#         return Response(data_dict)


# 修改密码
class UserPasswordView(APIView):
    def put(self, request):
        # 接收参数
        json_data = request.body.decode()
        data = json.loads(json_data)
        passward = data['password']
        # 获取用户对象
        try:
            request.user.set_password(passward)
            request.user.save()
        except Exception as e:
            return JsonResponse({'message': '数据库错误', 'success': False})

        logout(request)
        return JsonResponse({'message': 'ok', 'success': True})


# 关注与取消关注
class UserFansView(APIView):
    """关注与取消关注"""

    def post(self, request, id):
        # 关注
        # 获取用户对象
        user = request.user
        try:
            # 获取被关注用户对象
            idol = User.objects.get(id=id)
            # 添加关注
            user.idols.add(idol)
            user.save()
            return Response({'message': '关注成功',
                             'success': True})
        except Exception as e:
            return Response({'message': '关注失败',
                             'success': False})

    def put(self, request, id):
        # 取消关注
        # 获取用户对象
        user = request.user
        try:
            # 获取取消用户对象
            fans = User.objects.get(id=id)
            # 添加关注
            user.idols.remove(fans)
            user.save()
            return Response({'message': '取消成功',
                             'success': True})
        except Exception as e:
            return Response({'message': '取消失败',
                             'success': False})
